//
//  ViewController.m
//  TimeManager
//
//  Created by 刘凯敏 on 29/11/2016.
//  Copyright © 2016 刘凯敏. All rights reserved.
//

#import "DailyPlanHomePage.h"
#import "DPDetailModel.h"
#import "AddDPDetailViewController.h"
#import "EditDPDetailViewController.h"
#import "SZCalendarPicker.h"

//宏定义存储数据的文件的路径
#define ContactFilePath [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"]

@implementation DailyPlanHomePage

- (NSMutableArray *) contactArr{
    if(!_contactArr){
        //解码
        _contactArr = [NSKeyedUnarchiver unarchiveObjectWithFile:ContactFilePath];
        if(_contactArr == nil){
            _contactArr = [NSMutableArray array];
        }
    }
    return _contactArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self clearExtraLine];
    //得到当前的时间
    NSDate * currentDate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    //获取星期几
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components: NSCalendarUnitWeekday fromDate:[NSDate date]];
    long weekday = [componets weekday];
    NSArray *weekArray = @[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    NSString *weekStr = weekArray[weekday-1];
    //设置按钮显示日期
    [self.currentDate setTitle: [dateString stringByAppendingString:[@" "stringByAppendingString: weekStr ]] forState:UIControlStateNormal];// 添加文字
    //为UITableView控件设置dataSource和delegate
    self.DPDetailTable.dataSource = self;
    self.DPDetailTable.delegate = self;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//该方法的返回值决定指定分区内包含多少个表格行
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.contactArr.count;
}

//该方法返回值决定各表格行的控件
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
    DPDetailModel *contactModel = self.contactArr[indexPath.row];
    cell.textLabel.text = contactModel.name;
    cell.detailTextLabel.text = contactModel.place;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

//该方法的返回值将作为表格行的高度
- (CGFloat) tableView:(UITableView *) tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return  50;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    //拿到控制器并进行传值
    //设置代理对象
    id vc = segue.destinationViewController;
    //如果是跳转到添加联系人控制器
    if([vc isKindOfClass:[AddDPDetailViewController class]]){
        //设置代理
        AddDPDetailViewController *addVc = vc;
        addVc.delegate = self;
    }
    else if([vc isKindOfClass:[EditDPDetailViewController class]]){
        //取得选中那一行
        NSIndexPath *path = [self.DPDetailTable indexPathForSelectedRow];
        EditDPDetailViewController *editVc = vc;
        editVc.contactModel = self.contactArr[path.row];
        //设置代理，HomePage充当代理角色
        editVc.delegate = self;
    }
}

//添加
#pragma mark - AddVc delegate
-(void) addContact: (AddDPDetailViewController *) addVc didiAddContact:(DPDetailModel *) contact{
    //1.添加数据模型
    [self.contactArr addObject:contact];
    //2.刷新表视图
    [self.DPDetailTable reloadData];
    //3.归档
    [NSKeyedArchiver archiveRootObject:self.contactArr toFile:ContactFilePath];
}

//修改
#pragma mark -EditVc delegate
- (void) editContact:(EditDPDetailViewController *)editVC didSaveContact:(DPDetailModel *)contact{
    //刷新表视图
    [self.DPDetailTable reloadData];
    //归档
    [NSKeyedArchiver archiveRootObject:self.contactArr toFile:ContactFilePath];
}

//删除
#pragma mark - DeleteVc delegate
- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        //1.删除数据模型
        [self.contactArr removeObjectAtIndex:indexPath.row];
        //2.刷新表视图
        [self.DPDetailTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        //3.归档
        [NSKeyedArchiver archiveRootObject:self.contactArr toFile:ContactFilePath];
    }
}


#pragma mark - 去掉多余表格线
- (void) clearExtraLine{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    [self.DPDetailTable setTableFooterView:view];
}

- (IBAction)backAciton:(id)sender {
    //初始化
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否注销？" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    //添加按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //返回上一级控制器
        [self.navigationController popViewControllerAnimated:NO];
    }]];
    //弹出控制器
    [self presentViewController:alert animated:YES completion:NULL];
}

//日历插件
- (IBAction)showAction {
    SZCalendarPicker *calendarPicker = [SZCalendarPicker showOnView:self.view];
    calendarPicker.today = [NSDate date];
    calendarPicker.date = calendarPicker.today;
    calendarPicker.frame = CGRectMake(0, 100, self.view.frame.size.width, 352);
    calendarPicker.calendarBlock = ^(NSInteger day, NSInteger month, NSInteger year)
    {
        NSLog(@"%li-%li-%li", (long)year,(long)month,(long)day);
    };
}
@end
